/**
 * SQLite 数据库工具类
 * 提供本地数据库的增删改查操作
 * 支持数据同步、离线存储等功能
 * 遵循HTTP API数据格式规范，统一返回格式
 */

// 状态码定义
const DB_STATUS_CODES = {
  SUCCESS: 0,
  PARAM_ERROR: 1001,
  UNAUTHORIZED: 1002,
  NOT_FOUND: 1003,
  OPERATION_FAILED: 1004,
  SYSTEM_ERROR: 9999
}

// 统一响应格式
const createResponse = (code = DB_STATUS_CODES.SUCCESS, message = 'success', data = null) => {
  return {
    code,
    message,
    data
  }
}

// 统一错误处理
const handleError = (error, operation = '数据库操作') => {
  console.error(`${operation}失败:`, error)
  
  if (error.message && error.message.includes('参数')) {
    return createResponse(DB_STATUS_CODES.PARAM_ERROR, error.message, null)
  }
  
  if (error.message && error.message.includes('不存在')) {
    return createResponse(DB_STATUS_CODES.NOT_FOUND, error.message, null)
  }
  
  return createResponse(
    DB_STATUS_CODES.SYSTEM_ERROR,
    error.message || `${operation}失败`,
    null
  )
}

// 数据库配置
const DB_CONFIG = {
  name: 'tictac.db',
  version: '1.0',
  description: 'TicTac应用本地数据库',
  size: 5 * 1024 * 1024 // 5MB
}

// 表结构定义
const TABLE_SCHEMAS = {
  // 用户表
  users: `
    CREATE TABLE IF NOT EXISTS users (
      id TEXT PRIMARY KEY,
      username TEXT UNIQUE NOT NULL,
      email TEXT UNIQUE,
      nickname TEXT,
      avatar TEXT,
      phone TEXT,
      gender INTEGER DEFAULT 0,
      birthday TEXT,
      bio TEXT,
      settings TEXT,
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL,
      synced_at TEXT,
      is_deleted INTEGER DEFAULT 0
    )
  `,
  
  // 习惯表
  habits: `
    CREATE TABLE IF NOT EXISTS habits (
      id TEXT PRIMARY KEY,
      user_id TEXT NOT NULL,
      name TEXT NOT NULL,
      description TEXT,
      category_id TEXT,
      icon TEXT,
      color TEXT,
      type TEXT NOT NULL,
      frequency TEXT,
      target_value INTEGER,
      unit TEXT,
      reminder_enabled INTEGER DEFAULT 0,
      reminder_time TEXT,
      is_active INTEGER DEFAULT 1,
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL,
      synced_at TEXT,
      is_deleted INTEGER DEFAULT 0,
      FOREIGN KEY (user_id) REFERENCES users(id)
    )
  `,
  
  // 习惯记录表
  habit_records: `
    CREATE TABLE IF NOT EXISTS habit_records (
      id TEXT PRIMARY KEY,
      habit_id TEXT NOT NULL,
      date TEXT NOT NULL,
      value INTEGER DEFAULT 1,
      note TEXT,
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL,
      synced_at TEXT,
      is_deleted INTEGER DEFAULT 0,
      FOREIGN KEY (habit_id) REFERENCES habits(id),
      UNIQUE(habit_id, date)
    )
  `,
  
  // 财务账户表
  finance_accounts: `
    CREATE TABLE IF NOT EXISTS finance_accounts (
      id TEXT PRIMARY KEY,
      user_id TEXT NOT NULL,
      name TEXT NOT NULL,
      type TEXT NOT NULL,
      balance REAL DEFAULT 0,
      currency TEXT DEFAULT 'CNY',
      icon TEXT,
      color TEXT,
      is_active INTEGER DEFAULT 1,
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL,
      synced_at TEXT,
      is_deleted INTEGER DEFAULT 0,
      FOREIGN KEY (user_id) REFERENCES users(id)
    )
  `,
  
  // 财务交易表
  finance_transactions: `
    CREATE TABLE IF NOT EXISTS finance_transactions (
      id TEXT PRIMARY KEY,
      user_id TEXT NOT NULL,
      account_id TEXT NOT NULL,
      type TEXT NOT NULL,
      amount REAL NOT NULL,
      category_id TEXT,
      description TEXT,
      date TEXT NOT NULL,
      tags TEXT,
      location TEXT,
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL,
      synced_at TEXT,
      is_deleted INTEGER DEFAULT 0,
      FOREIGN KEY (user_id) REFERENCES users(id),
      FOREIGN KEY (account_id) REFERENCES finance_accounts(id)
    )
  `,
  
  // 时间记录表
  time_records: `
    CREATE TABLE IF NOT EXISTS time_records (
      id TEXT PRIMARY KEY,
      user_id TEXT NOT NULL,
      activity_name TEXT NOT NULL,
      category_id TEXT,
      start_time TEXT NOT NULL,
      end_time TEXT,
      duration INTEGER,
      description TEXT,
      tags TEXT,
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL,
      synced_at TEXT,
      is_deleted INTEGER DEFAULT 0,
      FOREIGN KEY (user_id) REFERENCES users(id)
    )
  `,
  
  // 待办事项表
  todos: `
    CREATE TABLE IF NOT EXISTS todos (
      id TEXT PRIMARY KEY,
      user_id TEXT NOT NULL,
      title TEXT NOT NULL,
      description TEXT,
      category_id TEXT,
      priority TEXT DEFAULT 'medium',
      status TEXT DEFAULT 'pending',
      tags TEXT,
      due_date TEXT,
      reminder TEXT,
      is_important INTEGER DEFAULT 0,
      is_urgent INTEGER DEFAULT 0,
      estimated_duration INTEGER,
      actual_duration INTEGER,
      progress INTEGER DEFAULT 0,
      completed_at TEXT,
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL,
      synced_at TEXT,
      is_deleted INTEGER DEFAULT 0,
      FOREIGN KEY (user_id) REFERENCES users(id)
    )
  `,
  
  // 同步日志表
  sync_logs: `
    CREATE TABLE IF NOT EXISTS sync_logs (
      id TEXT PRIMARY KEY,
      table_name TEXT NOT NULL,
      record_id TEXT NOT NULL,
      action TEXT NOT NULL,
      sync_status TEXT DEFAULT 'pending',
      error_message TEXT,
      created_at TEXT NOT NULL,
      synced_at TEXT
    )
  `
}

class DatabaseManager {
  constructor() {
    this.db = null
    this.isInitialized = false
  }

  /**
   * 初始化数据库
   * @returns {Promise<Object>} 统一响应格式
   */
  async init() {
    if (this.isInitialized) {
      return createResponse(DB_STATUS_CODES.SUCCESS, '数据库已初始化', { db: this.db })
    }

    try {
      // #ifdef APP-PLUS
      // App端使用SQLite
      this.db = plus.sqlite.openDatabase({
        name: DB_CONFIG.name,
        path: '_doc/' + DB_CONFIG.name
      })
      // #endif

      // #ifdef H5
      // H5端使用WebSQL或IndexedDB模拟
      this.db = await this.initWebDatabase()
      // #endif

      // #ifdef MP
      // 小程序端使用本地存储模拟
      this.db = this.initStorageDatabase()
      // #endif

      await this.createTables()
      this.isInitialized = true
      
      console.log('数据库初始化成功')
      return createResponse(DB_STATUS_CODES.SUCCESS, '数据库初始化成功', { db: this.db })
    } catch (error) {
      return handleError(error, '数据库初始化')
    }
  }

  /**
   * 初始化Web数据库（H5端）
   */
  async initWebDatabase() {
    return new Promise((resolve, reject) => {
      if (!window.openDatabase) {
        // 使用localStorage模拟
        resolve(this.initStorageDatabase())
        return
      }

      try {
        const db = window.openDatabase(
          DB_CONFIG.name,
          DB_CONFIG.version,
          DB_CONFIG.description,
          DB_CONFIG.size
        )
        resolve(db)
      } catch (error) {
        reject(error)
      }
    })
  }

  /**
   * 初始化存储数据库（小程序端和H5降级）
   */
  initStorageDatabase() {
    return {
      transaction: (callback) => {
        const tx = {
          executeSql: (sql, params, success, error) => {
            try {
              const result = this.executeStorageSQL(sql, params)
              if (success) success(tx, result)
            } catch (err) {
              if (error) error(tx, err)
            }
          }
        }
        callback(tx)
      }
    }
  }

  /**
   * 执行存储SQL（localStorage模拟）
   */
  executeStorageSQL(sql, params = []) {
    // 简化的SQL解析和执行
    // 实际项目中可以使用更完善的SQL解析库
    const sqlUpper = sql.toUpperCase().trim()
    
    if (sqlUpper.startsWith('CREATE TABLE')) {
      // 创建表操作，只需要记录表结构
      return { rowsAffected: 0 }
    }
    
    if (sqlUpper.startsWith('INSERT')) {
      // 插入操作
      return this.executeStorageInsert(sql, params)
    }
    
    if (sqlUpper.startsWith('SELECT')) {
      // 查询操作
      return this.executeStorageSelect(sql, params)
    }
    
    if (sqlUpper.startsWith('UPDATE')) {
      // 更新操作
      return this.executeStorageUpdate(sql, params)
    }
    
    if (sqlUpper.startsWith('DELETE')) {
      // 删除操作
      return this.executeStorageDelete(sql, params)
    }
    
    return { rowsAffected: 0 }
  }

  /**
   * 执行存储插入
   */
  executeStorageInsert(sql, params) {
    // 简化实现，实际项目中需要更完善的SQL解析
    const tableName = this.extractTableName(sql)
    const data = this.getStorageTableData(tableName)
    
    // 生成新记录（简化实现）
    const newRecord = {
      id: this.generateId(),
      ...this.parseInsertParams(sql, params)
    }
    
    data.push(newRecord)
    this.setStorageTableData(tableName, data)
    
    return {
      rowsAffected: 1,
      insertId: newRecord.id
    }
  }

  /**
   * 执行存储查询
   */
  executeStorageSelect(sql, params) {
    const tableName = this.extractTableName(sql)
    const data = this.getStorageTableData(tableName)
    
    // 检查是否是COUNT查询
    if (sql.toUpperCase().includes('COUNT(*)')) {
      const filteredData = this.applyWhereClause(data, sql, params)
      return {
        rows: {
          length: 1,
          item: (index) => ({ total: filteredData.length })
        }
      }
    }
    
    // 简化的查询实现
    const filteredData = this.applyWhereClause(data, sql, params)
    
    return {
      rows: {
        length: filteredData.length,
        item: (index) => filteredData[index]
      }
    }
  }

  /**
   * 执行存储更新
   */
  executeStorageUpdate(sql, params) {
    const tableName = this.extractTableName(sql)
    const data = this.getStorageTableData(tableName)
    
    // 简化的更新实现
    const updatedCount = this.applyUpdateClause(data, sql, params)
    this.setStorageTableData(tableName, data)
    
    return { rowsAffected: updatedCount }
  }

  /**
   * 执行存储删除
   */
  executeStorageDelete(sql, params) {
    const tableName = this.extractTableName(sql)
    const data = this.getStorageTableData(tableName)
    
    // 简化的删除实现（软删除）
    const deletedCount = this.applyDeleteClause(data, sql, params)
    this.setStorageTableData(tableName, data)
    
    return { rowsAffected: deletedCount }
  }

  /**
   * 获取存储表数据
   */
  getStorageTableData(tableName) {
    const key = `db_${tableName}`
    const data = uni.getStorageSync(key)
    return data ? JSON.parse(data) : []
  }

  /**
   * 设置存储表数据
   */
  setStorageTableData(tableName, data) {
    const key = `db_${tableName}`
    uni.setStorageSync(key, JSON.stringify(data))
  }

  /**
   * 提取表名
   */
  extractTableName(sql) {
    const match = sql.match(/(?:FROM|INTO|UPDATE)\s+([\w_]+)/i)
    return match ? match[1] : ''
  }

  /**
   * 解析插入参数
   */
  parseInsertParams(sql, params) {
    // sql示例："INSERT INTO habits (id, name, description, category, type, priority, targetValue, unit, reminderTime, reminderEnabled, created_at, updated_at, is_deleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
    // 解析字段名
    const fieldNames = sql.match(/\(([^)]+)\)/)[1].trim().split(', ')
    // 解析值
    const values = params
    // 合并字段名和值
    const data = fieldNames.reduce((acc, field, index) => {
      acc[field] = values[index]
      return acc
    }, {})
    
    // 处理默认值
    if (data.created_at === undefined) {
      data.created_at = new Date().toISOString()
    }
    if (data.updated_at === undefined) {
      data.updated_at = new Date().toISOString()
    }
    if (data.is_deleted === undefined) {
      data.is_deleted = 0
    }
    
    return data
  }

  /**
   * 应用WHERE子句
   */
  applyWhereClause(data, sql, params) {
    // 简化实现，处理常见的WHERE条件
    if (sql.includes('is_deleted = 0')) {
      return data.filter(item => !item.is_deleted || item.is_deleted === 0)
    }
    
    if (sql.includes('WHERE')) {
      // 更复杂的WHERE条件处理可以在这里扩展
      return data.filter(item => !item.is_deleted || item.is_deleted === 0)
    }
    
    // 默认过滤已删除的数据
    return data.filter(item => !item.is_deleted || item.is_deleted === 0)
  }

  /**
   * 应用UPDATE子句
   */
  applyUpdateClause(data, sql, params) {
    // 简化实现
    let count = 0
    data.forEach(item => {
      if (!item.is_deleted) {
        item.updated_at = new Date().toISOString()
        count++
      }
    })
    return count
  }

  /**
   * 应用DELETE子句
   */
  applyDeleteClause(data, sql, params) {
    // 软删除实现
    let count = 0
    data.forEach(item => {
      if (!item.is_deleted) {
        item.is_deleted = 1
        item.updated_at = new Date().toISOString()
        count++
      }
    })
    return count
  }

  /**
   * 生成ID
   */
  generateId() {
    return 'local_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
  }

  /**
   * 创建所有表
   */
  async createTables() {
    for (const [tableName, schema] of Object.entries(TABLE_SCHEMAS)) {
      await this.executeSql(schema)
    }
  }

  /**
   * 执行SQL语句
   */
  async executeSql(sql, params = []) {
    return new Promise((resolve, reject) => {
      this.db.transaction((tx) => {
        tx.executeSql(
          sql,
          params,
          (tx, result) => {
            resolve(result)
          },
          (tx, error) => {
            console.error('SQL执行错误:', error)
            reject(error)
          }
        )
      })
    })
  }

  /**
   * 查询数据
   * @param {string} sql SQL语句
   * @param {Array} params 参数
   * @returns {Promise<Object>} 统一响应格式
   */
  async query(sql, params = []) {
    try {
      if (!sql || typeof sql !== 'string') {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：SQL语句不能为空', null)
      }

      const result = await this.executeSql(sql, params)
      const rows = []
      
      for (let i = 0; i < result.rows.length; i++) {
        rows.push(result.rows.item(i))
      }
      
      return createResponse(DB_STATUS_CODES.SUCCESS, '查询成功', rows)
    } catch (error) {
      return handleError(error, '数据查询')
    }
  }

  /**
   * 插入数据
   * @param {string} tableName 表名
   * @param {Object} data 数据对象
   * @returns {Promise<Object>} 统一响应格式
   */
  async insert(tableName, data) {
    try {
      if (!tableName || typeof tableName !== 'string') {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：表名不能为空', null)
      }
      
      if (!data || typeof data !== 'object' || Object.keys(data).length === 0) {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：数据不能为空', null)
      }

      // 添加时间戳
      const insertData = {
        ...data,
        created_at: data.created_at || new Date().toISOString(),
        updated_at: data.updated_at || new Date().toISOString()
      }

      const fields = Object.keys(insertData)
      const values = Object.values(insertData)
      const placeholders = fields.map(() => '?').join(', ')
      
      const sql = `INSERT INTO ${tableName} (${fields.join(', ')}) VALUES (${placeholders})`
      
      const result = await this.executeSql(sql, values)
      const insertId = result.insertId || result.rowsAffected
      
      return createResponse(DB_STATUS_CODES.SUCCESS, '插入成功', { 
        id: insertId,
        affectedRows: result.rowsAffected 
      })
    } catch (error) {
      return handleError(error, '数据插入')
    }
  }

  /**
   * 更新数据
   * @param {string} tableName 表名
   * @param {Object} data 更新数据
   * @param {string} where WHERE条件
   * @param {Array} whereParams WHERE参数
   * @returns {Promise<Object>} 统一响应格式
   */
  async update(tableName, data, where, whereParams = []) {
    try {
      if (!tableName || typeof tableName !== 'string') {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：表名不能为空', null)
      }
      
      if (!data || typeof data !== 'object' || Object.keys(data).length === 0) {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：更新数据不能为空', null)
      }
      
      if (!where || typeof where !== 'string') {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：WHERE条件不能为空', null)
      }

      // 添加更新时间戳
      const updateData = {
        ...data,
        updated_at: new Date().toISOString()
      }

      const fields = Object.keys(updateData)
      const values = Object.values(updateData)
      const setClause = fields.map(field => `${field} = ?`).join(', ')
      
      const sql = `UPDATE ${tableName} SET ${setClause} WHERE ${where}`
      
      const result = await this.executeSql(sql, [...values, ...whereParams])
      
      if (result.rowsAffected === 0) {
        return createResponse(DB_STATUS_CODES.NOT_FOUND, '未找到要更新的数据', { affectedRows: 0 })
      }
      
      return createResponse(DB_STATUS_CODES.SUCCESS, '更新成功', { 
        affectedRows: result.rowsAffected 
      })
    } catch (error) {
      return handleError(error, '数据更新')
    }
  }

  /**
   * 删除数据（软删除）
   * @param {string} tableName 表名
   * @param {string} where WHERE条件
   * @param {Array} whereParams WHERE参数
   * @returns {Promise<Object>} 统一响应格式
   */
  async delete(tableName, where, whereParams = []) {
    try {
      if (!tableName || typeof tableName !== 'string') {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：表名不能为空', null)
      }
      
      if (!where || typeof where !== 'string') {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：WHERE条件不能为空', null)
      }

      const sql = `UPDATE ${tableName} SET is_deleted = 1, updated_at = ? WHERE ${where}`
      const result = await this.executeSql(sql, [new Date().toISOString(), ...whereParams])
      
      if (result.rowsAffected === 0) {
        return createResponse(DB_STATUS_CODES.NOT_FOUND, '未找到要删除的数据', { affectedRows: 0 })
      }
      
      return createResponse(DB_STATUS_CODES.SUCCESS, '删除成功', { 
        affectedRows: result.rowsAffected 
      })
    } catch (error) {
      return handleError(error, '数据删除')
    }
  }

  /**
   * 物理删除数据
   * @param {string} tableName 表名
   * @param {string} where WHERE条件
   * @param {Array} whereParams WHERE参数
   * @returns {Promise<Object>} 统一响应格式
   */
  async hardDelete(tableName, where, whereParams = []) {
    try {
      if (!tableName || typeof tableName !== 'string') {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：表名不能为空', null)
      }
      
      if (!where || typeof where !== 'string') {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：WHERE条件不能为空', null)
      }

      const sql = `DELETE FROM ${tableName} WHERE ${where}`
      const result = await this.executeSql(sql, whereParams)
      
      if (result.rowsAffected === 0) {
        return createResponse(DB_STATUS_CODES.NOT_FOUND, '未找到要删除的数据', { affectedRows: 0 })
      }
      
      return createResponse(DB_STATUS_CODES.SUCCESS, '物理删除成功', { 
        affectedRows: result.rowsAffected 
      })
    } catch (error) {
      return handleError(error, '数据物理删除')
    }
  }

  /**
   * 分页查询
   * @param {string} tableName 表名
   * @param {Object} options 查询选项
   * @returns {Promise<Object>} 统一响应格式，符合HTTP API规范
   */
  async paginate(tableName, options = {}) {
    try {
      if (!tableName || typeof tableName !== 'string') {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：表名不能为空', null)
      }

      const {
        page = 1,
        pageSize = 20,
        where = 'is_deleted = 0',
        whereParams = [],
        orderBy = 'created_at DESC'
      } = options
      
      // 参数验证
      if (page < 1 || pageSize < 1) {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：页码和页大小必须大于0', null)
      }
      
      if (pageSize > 100) {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：页大小不能超过100', null)
      }
      
      const offset = (page - 1) * pageSize
      
      // 查询总数
      const countSql = `SELECT COUNT(*) as total FROM ${tableName} WHERE ${where}`
      const countResponse = await this.query(countSql, whereParams)
      
      if (countResponse.code !== DB_STATUS_CODES.SUCCESS) {
        return countResponse
      }
      
      const total = (countResponse.data && countResponse.data[0] && typeof countResponse.data[0].total !== 'undefined') 
        ? countResponse.data[0].total 
        : 0
      
      // 查询数据
      const dataSql = `SELECT * FROM ${tableName} WHERE ${where} ORDER BY ${orderBy} LIMIT ? OFFSET ?`
      const dataResponse = await this.query(dataSql, [...whereParams, pageSize, offset])
      
      if (dataResponse.code !== DB_STATUS_CODES.SUCCESS) {
        return dataResponse
      }
      
      // 按照HTTP API规范返回分页数据
      const paginationData = {
        list: dataResponse.data || [],
        page,
        pageSize,
        total
      }
      
      return createResponse(DB_STATUS_CODES.SUCCESS, '分页查询成功', paginationData)
    } catch (error) {
      return handleError(error, '分页查询')
    }
  }

  /**
   * 开始事务
   */
  async beginTransaction() {
    return new Promise((resolve, reject) => {
      this.db.transaction((tx) => {
        resolve(tx)
      }, reject)
    })
  }

  /**
   * 清空表数据
   * @param {string} tableName 表名
   * @returns {Promise<Object>} 统一响应格式
   */
  async truncate(tableName) {
    try {
      if (!tableName || typeof tableName !== 'string') {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：表名不能为空', null)
      }

      const sql = `DELETE FROM ${tableName}`
      const result = await this.executeSql(sql)
      
      return createResponse(DB_STATUS_CODES.SUCCESS, '清空表成功', { 
        affectedRows: result.rowsAffected 
      })
    } catch (error) {
      return handleError(error, '清空表数据')
    }
  }

  /**
   * 获取表信息
   * @param {string} tableName 表名
   * @returns {Promise<Object>} 统一响应格式
   */
  async getTableInfo(tableName) {
    try {
      if (!tableName || typeof tableName !== 'string') {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：表名不能为空', null)
      }

      const sql = `PRAGMA table_info(${tableName})`
      return await this.query(sql)
    } catch (error) {
      return handleError(error, '获取表信息')
    }
  }

  /**
   * 数据库备份
   * @returns {Promise<Object>} 统一响应格式
   */
  async backup() {
    try {
      const backup = {}
      
      for (const tableName of Object.keys(TABLE_SCHEMAS)) {
        const response = await this.query(`SELECT * FROM ${tableName} WHERE is_deleted = 0`)
        if (response.code === DB_STATUS_CODES.SUCCESS) {
          backup[tableName] = response.data
        } else {
          console.warn(`备份表 ${tableName} 失败:`, response.message)
          backup[tableName] = []
        }
      }
      
      return createResponse(DB_STATUS_CODES.SUCCESS, '数据库备份成功', {
        backup,
        timestamp: new Date().toISOString(),
        tables: Object.keys(backup).length
      })
    } catch (error) {
      return handleError(error, '数据库备份')
    }
  }

  /**
   * 数据库恢复
   * @param {Object} backup 备份数据
   * @returns {Promise<Object>} 统一响应格式
   */
  async restore(backup) {
    try {
      if (!backup || typeof backup !== 'object') {
        return createResponse(DB_STATUS_CODES.PARAM_ERROR, '参数错误：备份数据不能为空', null)
      }

      const results = {}
      let successCount = 0
      let failCount = 0
      
      for (const [tableName, data] of Object.entries(backup)) {
        try {
          // 清空表
          const truncateResponse = await this.truncate(tableName)
          if (truncateResponse.code !== DB_STATUS_CODES.SUCCESS) {
            results[tableName] = { success: false, error: truncateResponse.message }
            failCount++
            continue
          }
          
          // 插入数据
          let insertedCount = 0
          for (const record of data) {
            const insertResponse = await this.insert(tableName, record)
            if (insertResponse.code === DB_STATUS_CODES.SUCCESS) {
              insertedCount++
            }
          }
          
          results[tableName] = { success: true, insertedCount }
          successCount++
        } catch (error) {
          results[tableName] = { success: false, error: error.message }
          failCount++
        }
      }
      
      return createResponse(DB_STATUS_CODES.SUCCESS, '数据库恢复完成', {
        results,
        successCount,
        failCount,
        timestamp: new Date().toISOString()
      })
    } catch (error) {
      return handleError(error, '数据库恢复')
    }
  }

  /**
   * 关闭数据库
   */
  close() {
    if (this.db) {
      // #ifdef APP-PLUS
      plus.sqlite.closeDatabase(this.db)
      // #endif
      
      this.db = null
      this.isInitialized = false
    }
  }
}

// 创建数据库管理器实例
const database = new DatabaseManager()

export default database
export { 
  DatabaseManager, 
  TABLE_SCHEMAS, 
  DB_CONFIG, 
  DB_STATUS_CODES,
  createResponse,
  handleError
}